package com.whjk.system.biz.controller;

import com.whjk.core.common.api.Result;
import com.whjk.core.security.config.FileUploadConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Api(value = "文件上传", tags = {"文件上传"})
@RestController
@RequestMapping(value = "files")
public class UploadController {

    @Autowired
    FileUploadConfig fileUploadConfig;

    /**
     * 常用图片格式 ^表示正则表达式开始，$表示正则表达式结束，这个正则表达式是 .叠加上jpeg/jpg/png/gif中的任意一个
     */
    public static final String REG_IMG_FORMAT = "^.+(.JPEG|.jpeg|.JPG|.jpg|.PNG|.png|.GIF|.gif)$";

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> testUpload(MultipartFile multipartFile) throws IOException {
        Assert.isTrue(multipartFile != null, "文件为空");
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss-SSS");
        String fileName = fmt.format(now) + "-" + multipartFile.getOriginalFilename();
        String path = now.getYear() + "/" + now.getMonthValue() + "/" + now.getDayOfMonth();
        //检查该路径对应的目录是否存在. 如果不存在则创建目录
        String savePath = "/" + path + "/" + fileName;
        //获取那个盘
        String property = System.getProperty("user.dir");
        String substring = property.substring(0, property.indexOf(":") + 1);
        boolean image = isImage(multipartFile);
        String url;
        if (image) {
            url = fileUploadConfig.getImgUrl();
        } else {
            url = fileUploadConfig.getTempleUrl();
        }
        String s = substring + fileUploadConfig.getUrl() + url + "/" + path;
        File file = new File(s);
        if (!file.exists()) {
            log.info("创建文件夹: " + s);
            // 创建完整的目录
            file.mkdirs();
        }
        File saveFile = new File(fileUploadConfig.getUrl() + url + savePath);

        // 将上传的文件复制到指定目录
        FileCopyUtils.copy(multipartFile.getBytes(), saveFile);
        // 返回给前端的图片保存路径；前台可以根据返回的路径拼接完整地址，即可在浏览器上预览该图片
        log.info("文件地址:" + url + savePath);
        return Result.ok(url + savePath);
    }


    /**
     * 判断MultipartFile对象是否为图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(MultipartFile file) {
        Matcher matcher = Pattern.compile(REG_IMG_FORMAT).matcher(Objects.requireNonNull(file.getOriginalFilename()));
        return matcher.find();
    }

    /**
     * 判断File对象是否为图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(File file) {
        Matcher matcher = Pattern.compile(REG_IMG_FORMAT).matcher(file.getName());
        return matcher.find();
    }
}
